package demo14_ForkJoin;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author kunkun
 * @className Test02_ForkJoin
 * @Description 使用ForkJoin加速计算
 * @date 2025/3/6 22:19
 */
public class Test02_ForkJoin extends RecursiveTask<Long> {

    Long start = 0L;
    Long end = 10_0000_0000L;
    Long threshold = 1_0000L;

    public Test02_ForkJoin(Long start,Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if(end-start<threshold){        //设置递归停止条件
            Long sum = 0L;
            for (Long i = start; i <= end; i++) {
                sum+=i;
            }
            return sum;
        }else{      //继续分隔任务
            Long middle =(start+end)/2;
            Test02_ForkJoin task1 = new Test02_ForkJoin(start, middle);//分割
            Test02_ForkJoin task2 = new Test02_ForkJoin(middle+1, end);//分隔
            task1.fork();
            task2.fork();
            return task1.join()+task2.join();   //合并
        }
    }

    public static void main(String[] args) {

        Long startTime = System.currentTimeMillis();

        //1. 创建ForkJoinPool类，用于执行ForkJoinTask
        ForkJoinPool forkJoinPool = new ForkJoinPool();


        //2. 构建ForkJoinTask对象
        Test02_ForkJoin task = new Test02_ForkJoin( 0L, 10_0000_0000L);

        //3. 执行任务
        Long sum = forkJoinPool.invoke(task);
        Long endTime = System.currentTimeMillis();

        System.out.println("sum="+sum);
        System.out.println("expend time:"+(endTime-startTime)+"ms");    //5179ms



    }



}
